from django.db import models
from django.contrib.auth.models import User
from apps.core.models import Template


class TemplateUsageLog(models.Model):
    """模板使用日志"""
    
    STATUS_CHOICES = [
        ('success', '成功'),
        ('failed', '失败'),
        ('processing', '处理中'),
    ]
    
    template = models.ForeignKey(Template, on_delete=models.CASCADE, related_name='usage_logs', verbose_name='使用的模板')
    user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, verbose_name='使用者')
    
    # 处理信息
    input_file_name = models.CharField(max_length=500, verbose_name='输入文件名')
    output_file_name = models.CharField(max_length=500, blank=True, verbose_name='输出文件名')
    
    # 处理结果
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='processing', verbose_name='处理状态')
    processed_rows = models.IntegerField(default=0, verbose_name='处理行数')
    error_message = models.TextField(blank=True, verbose_name='错误信息')
    
    # 处理时间
    start_time = models.DateTimeField(auto_now_add=True, verbose_name='开始时间')
    end_time = models.DateTimeField(null=True, blank=True, verbose_name='结束时间')
    
    # 处理配置快照
    config_snapshot = models.JSONField(default=dict, blank=True, verbose_name='配置快照')
    
    class Meta:
        verbose_name = '模板使用日志'
        verbose_name_plural = '模板使用日志'
        ordering = ['-start_time']
    
    def __str__(self):
        return f'{self.template.name} - {self.start_time.strftime("%Y-%m-%d %H:%M")}'  
    
    @property
    def duration(self):
        """处理耗时"""
        if self.end_time and self.start_time:
            return self.end_time - self.start_time
        return None
